package com.utooo.bid.service;

import cn.hutool.json.JSONUtil;
import com.utooo.bid.config.ModelConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class AIService {
    
    private final ModelConfig modelConfig;
    private final OkHttpClient okHttpClient = new OkHttpClient();

    public String invokeAi(String prompt) throws IOException {

        // 构建请求体
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("model", modelConfig.getSiliconflow().getModel());

        Map<String, String> message = new HashMap<>();
        message.put("role", "user");
        message.put("content", prompt);

        requestMap.put("messages", new Map[] {message});
        // 是否将生成的文本流式返回。默认为False。
        requestMap.put("stream", false);
        // 生成文本的标志，当生成的文本中出现该标志时，自动停止生成
        requestMap.put("stop", null);
        // 生成文本的随机度量程度。值越高，则生成结果更随机
        requestMap.put("temperature", 0.7);
        // 与温度类似，控制生成文本的随机程度。默认为1，越高则生成的文本越随机。
        requestMap.put("top_p", 0.7);
        requestMap.put("top_k", 50);
        // 控制生成文本中特定单词（比如人名）出现的频率。默认为0。
        requestMap.put("frequency_penalty", 0.5);
        // 生成文本中最大的 token 数量
        requestMap.put("max_tokens", 512);
        requestMap.put("response_format", Map.of("type", "json_object"));
        String requestBody = JSONUtil.toJsonStr(requestMap);

        MediaType mediaType = MediaType.parse("application/json");
        Request request = new Request.Builder()
                .url(modelConfig.getSiliconflow().getBaseUrl() + "/v1/chat/completions")
                .addHeader("Authorization", "Bearer " + modelConfig.getSiliconflow().getApiKey())
                .post(RequestBody.create(requestBody, mediaType))
                .build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected response " + response);
            }
            return response.body().string();
        }
    }
}